<?php
header('Content-type: application/json');
$gitUrl = 'https://gitee.com/youngxj0/giteeImages';

$fileExt=['gif','jpeg','jpg','png'];


if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {exit;}

if(isset($_FILES["file"])&&$_FILES["file"]){
	$multipart = true;
	$file = $_FILES["file"]["tmp_name"];
}elseif(isset($_GET['img'])&&$_GET['img']){
	$multipart = false;
	$file = $_GET['img'];
}else{
	echo echoJson('404','请勿直接访问');
}

$fileExtension=pathinfo($_FILES['file']['name'])['extension'];
if(!in_array($fileExtension,$fileExt)){
	echo echoJson('201','仅限上传图片');
}

if (isset($file) && $file != "") {


	$fileName = md5(rand(10000,99999)).'.'.$fileExtension;

	$move = move_uploaded_file($file,$fileName);
	$ip = getIp();

	$cmd = 'git add '.$fileName.';';
	$cmd.= "git commit -m '".$ip."';";
	$cmd.= 'git push';

	if($move){
		chgrp($fileName,'root');
		shell_exec($cmd);
		$imgUrl = $gitUrl.'/raw/master/'.$fileName;
			// https://gitee.com/youngxj0/giteeImages/raw/master/mmexport1542338277584.jpg
		echo echoJson('200','上传成功',array('imgUrl'=>$imgUrl,'cmd'=>$cmd));
		
	}else{
		echo echoJson('201','图片保存失败');
	}

}else{
	echo echoJson('201','上传错误');
}


function echoJson($code='200',$msg='上传成功',$data=[]){
	exit(json_encode(array('code'=>$code,'msg'=>$msg,'data'=>$data)));
}

function getIp(){
	$unknown = 'unknown';
	if ( isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown) ) {
		$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	} elseif ( isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown) ) {
		$ip = $_SERVER['REMOTE_ADDR'];
	}
	$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
	if (false !== strpos($ip, ','))
		$ip = reset(explode(',', $ip));
	return $ip;
}
